var email = require('../config.js').email
var nodemailer = require('nodemailer')
var logger = require('./log4js').getLogger()
var debuglogger = require('./log4js').getLogger('debug')

var transporter = nodemailer.createTransport({
  host: email.host,
  secureConnection: true, // use SSL
  port: 465,
  secure: true, // secure:true for port 465, secure:false for port 587
  auth: {
    user: email.user,
    pass: email.password
  }
})

/**
 * 发送邮件
 * @param contents
 */
module.exports = function(subject, contents, mail, callback) {
  transporter.sendMail(
    {
      from: email.user,
      to: mail,
      subject: subject,
      text: contents || 'is test!'
    },
    function(error, response) {
      if (error) {
        debuglogger.debug(error)
      } else {
        logger.info(
          'Message sent to ' + mail + ' success: ' + response.response
        )
      }

      transporter.close() // 如果没用，关闭连接池
      callback() //回调
    }
  )
}
